package com.warrior.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.warrior.Exception.ProjectException;
import com.warrior.configer.ConfigHelper;
import com.warrior.entity.ActivityContentEntity;
import com.warrior.entity.ActivityEntity;
import com.warrior.service.ActivityService;
import com.warrior.service.UtilsTools;
import com.warrior.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by shawn on 2017/4/24.
 */
@Controller
@RequestMapping("/admin")
public class AdminActivityController {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private UtilsTools utilsTools;


    /**
     * 活动添加页面
     *
     * @param request  request
     * @param response response
     * @return ModelAndView
     */
    @RequestMapping("/activity_page")
    public ModelAndView activityPage(HttpServletRequest request, HttpServletResponse response, String activityId) {
        ModelAndView mv = new CModelAndView("/admin/activity_edit", request, response);
        ActivityEntity activityEntity = this.activityService.findActivityById(activityId);
        mv.addObject("activityEntity", activityEntity);
        return mv;
    }


    /**
     * 添加一个活动
     *
     * @param activityLocation     记录活动场地
     * @param activityName         记录活动名称
     * @param activitySequence     活动排序
     * @param activityType         记录活动类型,0表示积分排名赛,1表示系列赛
     * @param isRecommend          是否被推荐,0表示未推荐活动,1表示推荐活动
     * @param activityTime         记录活动开始的时间
     * @param applyDeadLine        记录报名截止日期
     * @param teamUpperLimit       队伍报名上限
     * @param isNew                查看是否为新活动,0表示否,1表示是
     * @param activityStatus       查看活动状态 1表示报名中,2表示备战中,3表示活动结束,默认0
     * @param activityIntroduction 活动介绍
     * @param request              request
     * @return String
     */
    @RequestMapping(value = "/add_activity", method = RequestMethod.POST)
    @ResponseBody
    public String addActivity(String activityId, String activityLocation, String activityName, String activitySequence, String activityType, String isRecommend, String activityTime, String applyDeadLine
            , String teamUpperLimit, String isNew, String activityStatus, String activityIntroduction, HttpServletRequest request) {
        ActivityEntity activityEntity;
        if (null == activityId || "".equals(activityId)) {
            activityEntity = new ActivityEntity();
            activityEntity.setId("A-" + UUID.randomUUID().toString().replace("-", ""));
        } else {
            activityEntity = this.activityService.findActivityById(activityId);
        }
        DateUtil dateUtil = new DateUtil();
        activityEntity.setUpdateAt(dateUtil.Date2Timestamp(new Date()));
        activityEntity.setCreatedAt(dateUtil.Date2Timestamp(new Date()));
        activityEntity.setCreatedBy("admin");
        activityEntity.setUpdateBy("admin");
        activityEntity.setParentId("");
        activityEntity.setActivityLocation(activityLocation);
        activityEntity.setActivityName(activityName);
        activityEntity.setActivitySequence(CommonUtils.String2Int(activitySequence));
        activityEntity.setActivityType(CommonUtils.String2Int(activityType));
        activityEntity.setIsRecommend(CommonUtils.String2Int(isRecommend));
        activityEntity.setApplyDeadLine(dateUtil.String2Timestamp(applyDeadLine));
        activityEntity.setActivityTime(dateUtil.String2Timestamp(activityTime));
        activityEntity.setTeamUpperLimit(CommonUtils.String2Int(teamUpperLimit));
        activityEntity.setIsNew(CommonUtils.String2Int(isNew));
        activityEntity.setActivityStatus(CommonUtils.String2Int(activityStatus));
        activityEntity.setActivityIntroduction(activityIntroduction);
        // 图片上传开始
        String uploadFilePath = ConfigHelper.getConfig().getString("upload.path");
        String saveFilePathName = request.getSession().getServletContext()
                .getRealPath("/") + uploadFilePath + "/User_photo";
        Map map;
        String fileName = "";
        try {
            map = UploadUtils.saveFileToServer(request, "photo", saveFilePathName,
                    fileName, null);
            if (fileName.equals("")) {
                if (map.get("fileName") != "") {
                    fileName = (String) map.get("fileName");
                    String savePath = "/upload/User_photo/" + fileName;
                    activityEntity.setPicPath(savePath);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.activityService.saveNewActivity(activityEntity);
        String returnMap = null;
        try {
            returnMap = ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * 查看该活动内容
     *
     * @param activityId 该活动id
     * @param request    req
     * @param response   resp
     * @return
     */
    @RequestMapping("/activityContent")
    public ModelAndView findActivityContent(String activityId, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new CModelAndView("/admin/activity_detail_edit", request, response);
        if (null != activityId) {
            List<ActivityContentEntity> activityContentEntities = this.activityService.findAllContentByActivityId(activityId);
            mv.addObject("activityContentEntities", activityContentEntities);
        }
        mv.addObject("utilsTools",utilsTools);
        return mv;
    }

    /**
     * 编辑/添加一个活动内容
     *
     * @param activityContentId
     * @param text
     * @param picPath
     * @param videoPath
     * @param sequence
     * @return
     */
    @RequestMapping("/activityContentEdit")
    @ResponseBody
    public String editActivityContent(HttpServletRequest request, String activityContentId, String text, String picPath, String videoPath, String sequence,String activityId) {
        ActivityContentEntity activityContentEntity;
        DateUtil dateUtil = new DateUtil();
        if (null != activityContentId && !"".equals(activityContentId)) {
            activityContentEntity = this.activityService.findActivityContentByContentId(activityContentId);
        } else {
            activityContentEntity = new ActivityContentEntity();
            activityContentEntity.setId("AC-" + UUID.randomUUID().toString().replace("-", ""));
            activityContentEntity.setCreatedAt(dateUtil.Date2Timestamp(new Date()));
        }
        activityContentEntity.setActivityText(text);
        activityContentEntity.setActivityVideoPath(videoPath);
        activityContentEntity.setUpdateAt(dateUtil.Date2Timestamp(new Date()));
        activityContentEntity.setCreatedBy("admin");
        activityContentEntity.setUpdateBy("admin");
        if (null!=picPath){
            // 图片上传开始
            String uploadFilePath = ConfigHelper.getConfig().getString("upload.path");
            String saveFilePathName = request.getSession().getServletContext()
                    .getRealPath("/") + uploadFilePath + "/User_photo";
            Map map;
            String fileName = "";
            try {
                map = UploadUtils.saveFileToServer(request, "photo", saveFilePathName,
                        fileName, null);
                if (fileName.equals("")) {
                    if (map.get("fileName") != "") {
                        fileName = (String) map.get("fileName");
                        String savePath = "/upload/User_photo/" + fileName;
                        activityContentEntity.setActivityPicPath(savePath);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        activityContentEntity.setActivitySequence(CommonUtils.String2Int(sequence));
        ActivityEntity activityEntity = this.activityService.findActivityById(activityId);
        activityContentEntity.setActivityByActivityId(activityEntity);
        this.activityService.saveActivityContent(activityContentEntity);
        String returnMap = null;
        try {
            returnMap = ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * 删除活动内容
     *
     * @param contentId
     * @return
     */
    @RequestMapping(value = "/deleteActivityContent", method = RequestMethod.DELETE)
    @ResponseBody
    public String deleteActivityContent(String contentId) {
        this.activityService.deletedActivityContent(contentId);
        String returnMap = null;
        try {
            returnMap = ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * 删除活动
     *
     * @param activityId 活动id
     * @return
     */
    @RequestMapping(value = "/deleteActivity", method = RequestMethod.DELETE)
    @ResponseBody
    public String deleteActivity(String activityId) {
        try {
            this.activityService.deletedActivity(activityId);
        } catch (ProjectException e) {
            e.printStackTrace();
        }
        String returnMap = null;
        try {
            returnMap = ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;


    }


    /**
     * 活动列表页
     *
     * @param request   req
     * @param response  resp
     * @param size      页码数
     * @param page      当前页
     * @param orderType 排序类型
     * @param type      活动分类 0表示积分排名赛,1表示系列赛
     * @return
     */
    @RequestMapping(value = "/listAllActivity", method = RequestMethod.GET)
    public ModelAndView listAllActivity(HttpServletRequest request, HttpServletResponse response, String size, String page, String orderType, String type) {
        ModelAndView mv = new CModelAndView("/admin/activity_list", request, response);
        if (null == page || "".equals(page)) {
            page = "0";
        }
        Page<ActivityEntity> activityEntities = this.activityService.listActivityByActivityType(CommonUtils.String2Int(size), CommonUtils.String2Int(page), CommonUtils.String2Int(type), orderType);
        mv.addObject("activityEntities", activityEntities);
        return mv;
    }


}
